package com.zhx.basis.netty;

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class ChannelDemo {

    public static void main(String[] args) {
        //解决乱码问题
        Charset utf8Charset = Charset.forName("UTF-8");
        File file = null;
        try {
            //获取resources中的文件
            file=  ResourceUtils.getFile("classpath:ChannelDemotxt.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try (FileChannel channel = new FileInputStream(file).getChannel()) {
            //缓冲区  2进制,防止截取字节不正常
            ByteBuffer buffer = ByteBuffer.allocate(16);
            while (true){
                int read = channel.read(buffer);
                if (read==-1){
                    break;
                }
                buffer.flip();//切换到读模式
//                while (buffer.hasRemaining()){//是否还有剩余内容
//                    byte b = buffer.get();
//                    System.out.print((char)b);
//                }
                String s = utf8Charset.decode(buffer).toString();
                System.out.print(s);
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
